<?php

namespace App\Models\Wechat;

use App\Models\Model;

class WechatChannel extends Model
{
    protected $table = 'wechat_channel';

    public function getTicket()
    {
        $current = time();

        try{
            $app = app('wechat.official_account');
            if($this->channel_type == 1){
                $cnt = static::where(['channel_type'=>1])->count() + 1;
                $channel_code = 'forever_'.$cnt ;
                $response = $app->qrcode->forever($channel_code);
                $expire_at = 0;
            }else{
                $cnt = static::where(['channel_type'=>0])->count() + 1;
                $channel_code = 'forever_'.$cnt ;
                $response = $app->qrcode->temporary($channel_code);
                $expire_at = $current + $response->expire_seconds;
            }
            $this->ticket = $response->ticket;
            $this->channel_code = $channel_code;
            $this->expire_at = $expire_at;

            return $this->save();

        }catch (\Exception $exception){

            return false;
        }
    }

    public function content()
    {
        return $this->hasOne(ReplyContent::class,'id','reply_id');
    }
}
